package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mq.http.model.TopicMessage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.GoodsTop;
import com.eco.fanliapp.rocketmq.RocketConfig;
import com.eco.fanliapp.rocketmq.RocketmqProducerInit;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.SessionController;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.AppGoodsVo;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo.NTbkItem;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo.TbkPrivilege;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.taobao.api.response.TbkPrivilegeGetResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品主 服务层实现
 *
 * @author xiaoxx
 * @date 2019-04-25
 */
@Service
public class AppGoodsServiceImpl extends ServiceImpl<AppGoodsMapper, AppGoods> implements IAppGoodsService {

    private static final Logger log = LoggerFactory.getLogger(AppGoodsServiceImpl.class);
    @Autowired
    private AppGoodsMapper appGoodsMapper;

    @Autowired
    private IGoodsTopService iGoodsTopService;

    @Autowired
    private FindItemIdUtils taoBaoUtils;
    @Autowired
    private ITaoBaoService taoBaoService;
    @Autowired
    private SessionController sessionController;

    @Autowired
    private IUserCashschemeService userCashschemeService;

    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;

    @Autowired
    private ISyLabelTypeService iSyLabelTypeService;

    @Autowired
    private RocketmqProducerInit rocketmqProducerInit;
    @Autowired
    private RedisTemplateService redisTemplateService;


    /**
     * 查询商品主信息
     *
     * @param tableId 商品主ID
     * @return 商品主信息
     */
    @Override
    public AppGoods selectAppGoodsById(Long tableId) {
        return appGoodsMapper.selectAppGoodsById(tableId);
    }

    /**
     * 查询商品主列表
     *
     * @param appGoods 商品主信息
     * @return 商品主集合
     */
    @Override
    public List<AppGoods> selectAppGoodsList(AppGoods appGoods) {
        return appGoodsMapper.selectAppGoodsList(appGoods);
    }

    /**
     * 新增商品主
     *
     * @param appGoods 商品主信息
     * @return 结果
     */
    @Override
    public int insertAppGoods(AppGoods appGoods) {
        return appGoodsMapper.insertAppGoods(appGoods);
    }

    /**
     * 修改商品主
     *
     * @param appGoods 商品主信息
     * @return 结果
     */
    @Override
    public int updateAppGoods(AppGoods appGoods) {
        String fixedSort_key = "app_fixedSortGoods_list";
        if (appGoods.getItemid() != null) {
            if (redisTemplateService.hasKey(fixedSort_key)) {
                Map<String, Integer> map = redisTemplateService.getMap(fixedSort_key, Map.class);
                int i = 0;
                int y = 0;
                for (String key : map.keySet()) {
                    if (map.get(key) == appGoods.getFixedSort()) {
                        return 2;
                    }
                    if (key.equals(appGoods.getItemid()) && appGoods.getFixedSort() != -1) {
                        i++;
                    } else if (!key.equals(appGoods.getItemid()) && appGoods.getFixedSort() != -1) {
                        i++;
                    } else if (key.equals(appGoods.getItemid()) && appGoods.getFixedSort() == -1) {
                        y++;
                    }
                }
                if (i > 0) {
                    map.put(appGoods.getItemid(), appGoods.getFixedSort());
                    redisTemplateService.setMap(fixedSort_key, map, 0);
                }
                if (y > 0) {
                    redisTemplateService.delMapField(fixedSort_key, appGoods.getItemid());
                }
            } else {
                if (appGoods.getFixedSort() != -1) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(appGoods.getItemid(), appGoods.getFixedSort());
                    redisTemplateService.setMap(fixedSort_key, map, 0);
                }
            }
        }
        List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
        taoBaoService.getRedisRecommendGoodsList(appGoodsList);
//        redisTemplateService.batchDel("app_recommendGoods_lists" + 20 + "_" + 1,
//                "app_recommendGoods_lists" + 20 + "_" + 2,
//                "app_recommendGoods_lists" + 40 + "_" + 1,
//                "app_recommendGoods_lists" + 40 + "_" + 2);
        return appGoodsMapper.updateAppGoods(appGoods);
    }

    /**
     * 逻辑删除
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int updateAppGoodsByIds(String ids) {
        return appGoodsMapper.updateAppGoodsByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商品主对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAppGoodsByIds(String ids) {
        return appGoodsMapper.deleteAppGoodsByIds(Convert.toStrArray(ids));
    }

    @Override
    public int deleteAppGoodsByItemid(String ids) {
        return appGoodsMapper.deleteAppGoodsByItemid(Convert.toStrArray(ids));
    }

    /**
     * 根据商品id查询商品详情
     *
     * @param itemId
     * @return
     */
    @Override
    public AppGoods findAppGoodsByItemId(String itemId) {
        return appGoodsMapper.findAppGoodsByItemId(itemId);
    }

    @Override
    public List<AppGoods> selectAppGoodsListLIMIT100(Long start, Long end) {
        // TODO Auto-generated method stub
        return appGoodsMapper.selectAppGoodsListLIMIT100(start, end);
    }

    @Override
    public List<AppGoods> selectAppGoodsListsINFree(
            Integer type, Integer start, Integer back, Integer cid, Integer sort, Integer companyId) {
        // TODO Auto-generated method selectAppGoodsLists
        return appGoodsMapper.selectAppGoodsListAll(type, start, back, cid, sort, companyId);
    }

    @Override
    public List<AppGoods> selectAppGoodsByTaobaoImageIsNull() {
        // TODO Auto-generated method stub
        return appGoodsMapper.selectAppGoodsByTaobaoImageIsNull();
    }

    @Override
    public int deleteAppGoodsById(Long tableId) {
        // TODO Auto-generated method deleteAppGoodsById
        return appGoodsMapper.deleteAppGoodsById(tableId);
    }

    @Override
    public List<AppGoods> selectAppGoodsByItemId(Long numIid) {
        // TODO Auto-generated method selectAppGoodsByItemId
        return appGoodsMapper.selectAppGoodsByItemId(numIid);
    }

    @Override
    public List<AppGoods> selectAppGoodsListAll() {
        // TODO Auto-generated method stub
        return appGoodsMapper.deleteAppGoodsListAll();
    }

    @Override
    public List<AppGoods> selectAppGoodsListsNotFree(Integer type, Integer start, Integer back, Integer cid, Integer recommend,
                                                     Integer sort, Integer companyId) {
        // TODO Auto-generated method selectAppGoodsListsNotFree 不查询免单商品
        return appGoodsMapper.selectAppGoodsListsNotFree(type, start, back, cid, recommend, sort, companyId);
    }

    @Override
    public List<AppGoods> selectAppGoodsFreeList(
            Integer type, Integer cid, Integer start, Integer back, Long userId, Integer companyId) {
        // TODO Auto-generated method selectAppGoodsFreeList 查询免单商品
        return appGoodsMapper.selectAppGoodsFreeList(type, cid, start, back, userId, companyId);
    }

    @Override
    public ServerResponse addAppGoods(AppGoods appGoods, Integer userId) {
        String fqcat = appGoods.getFqcat();
        String itemId = appGoods.getItemid();
        if ("http".contains(itemId)) {
            itemId = itemId.substring(itemId.lastIndexOf("=") + 1);
        }
        String itempic = appGoods.getItempic();
        String itemtitle = appGoods.getItemtitle();
//        String fqcat = appGoods.getFqcat();
        //根据商品id查询商品是否存在
        Integer appGoodsNum = appGoodsMapper.selectCountByItemId(itemId);
//        if (appGoodsNum > 0) {
//            DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemId);
//            AppGoods goods = null;
//            HaoDanKuItemInfo info = null;
//            int type = 0;
//            if (dtkResponse != null && dtkResponse.getCode() == 0 && dtkResponse.getData() != null) {
//                goods = HDKUtils.getAppGoodsFromDTK(dtkResponse.getData());
//                type = 1;
//            }
//            if (goods == null) {
//                //如果不存在去好单库查询商品
//                info = taoBaoUtils.getHaoDanKuItemId(itemId);
//                if (info != null && info.getData() != null) {
//                    goods = HDKUtils.getAppGoodsFromHDK(info.getData());
//                    type = 2;
//                }
//            }
//            appGoods.setCouponstarttime(goods.getCouponstarttime());
//            appGoods.setCouponendtime(goods.getCouponendtime());
//            appGoods.setItemprice(goods.getItemprice());
////            int i = appGoodsMapper.updateBatchByItemId(goods);
//            int i = appGoodsMapper.updateGoodsByItemId(itemId, appGoods.getRecommend() == null ? 0 : appGoods.getRecommend(), goods.getActivityType() == null ? "" : goods.getActivityType(), goods.getStartTime() == null ? "0" : goods.getStartTime(), goods.getEndTime() == null ? "0" : goods.getEndTime());
//
//            if (i > 0) {
//                if (appGoods.getRecommend() != null && appGoods.getRecommend() == 1) {
//                    if (type == 1) {
//                        iSyLabelTypeService.savaDTKLabel(dtkResponse.getData());
//                    } else if (type == 2) {
//                        iSyLabelTypeService.savaHDKLabel(info.getData());
//                    }
//                }
//                //更新商品lucene索引
//                updateIndex(goods, "update");
////                this.updateAppGoods(appGoods);
//            }
//            return ServerResponse.createBySuccessCodeMessage(200, "该商品已存在,更新了商品信息!");
//        }
        AppCompany com = userCashschemeService.findCompanyAll();//查询公司加缓存
        DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemId);
        if (dtkResponse != null && dtkResponse.getCode() == 0 && dtkResponse.getData() != null) {

            AppGoods goods = HDKUtils.getAppGoodsFromDTK(dtkResponse.getData());
            goods.setAddUserId(userId);
            goods = getMoneyInfoByGoodsId(com, goods);
            if (StringUtils.isNotNull(itempic)) {
                goods.setItempic(itempic);
            }
            if (StringUtils.isNotNull(itemtitle)) {
                goods.setItemshorttitle(itemtitle);
            }

            if (StringUtils.isNotNull(fqcat)) {
                goods.setFqcat(fqcat);
            }
            if (appGoods.getRecommend() != null && appGoods.getRecommend() != null) {
                goods.setRecommend(appGoods.getRecommend());
            }
            goods.setSort(appGoods.getSort());
            goods.setMsg(appGoods.getMsg());
            if (appGoodsNum > 0) {
                int i = appGoodsMapper.updateBatchByItemId(goods);
                if (i > 0) {
                    if (appGoods.getRecommend() != null && appGoods.getRecommend() == 1) {
                        iSyLabelTypeService.savaDTKLabel(dtkResponse.getData());
                    }
                    //更新商品lucene索引
                    updateIndex(goods, "update");
                }
                return ServerResponse.createBySuccessCodeMessage(200, "该商品已存在,更新了商品信息!");
            } else {

                if (goods.getItemendprice() < 0) {
                    return ServerResponse.createByErrorMessage("商品添加失败");
                }
                int i = appGoodsMapper.insertAppGoods(goods);
                if (i > 0) {
                    if (appGoods.getRecommend() != null && appGoods.getRecommend() == 1) {
                        iSyLabelTypeService.savaDTKLabel(dtkResponse.getData());
                    }
                    //更新商品lucene索引
                    updateIndex(goods, "add");
                    // this.updateAppGoods(goods);
                    return ServerResponse.createBySuccessCodeMessage(200, "商品添加成功，从大淘客拉取");
                } else {
                    return ServerResponse.createByErrorMessage("商品添加失败，从大淘客拉取商品失败！");
                }
            }

        } else {
            //如果不存在去好单库查询商品
            HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(itemId);

            if (info != null && info.getCode() == 1 && info.getData() != null) {

                AppGoods goods = HDKUtils.getAppGoodsFromHDK(info.getData());
                goods.setAddUserId(userId);
                goods = getMoneyInfoByGoodsId(com, goods);
                if (StringUtils.isNotNull(itempic)) {
                    goods.setItempic(itempic);
                }
                if (StringUtils.isNotNull(itemtitle)) {
                    goods.setItemshorttitle(itemtitle);
                }

                if (StringUtils.isNotNull(fqcat)) {
                    goods.setFqcat(fqcat);
                }
                if (appGoods.getRecommend() != null) {
                    goods.setRecommend(appGoods.getRecommend());
                }
                goods.setSort(appGoods.getSort());
                goods.setMsg(appGoods.getMsg());
//            goods.setCreateTime(new Timestamp(System.currentTimeMillis()));
//            goods.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                if (appGoodsNum > 0) {
                    int i = appGoodsMapper.updateBatchByItemId(goods);
                    if (i > 0) {
                        if (appGoods.getRecommend() != null && appGoods.getRecommend() == 1) {
                            iSyLabelTypeService.savaHDKLabel(info.getData());
                        }
                        //更新商品lucene索引
                        updateIndex(goods, "update");
                    }
                    return ServerResponse.createBySuccessCodeMessage(200, "该商品已存在,更新了商品信息!");
                } else {
                    if (goods.getItemendprice() < 0) {
                        return ServerResponse.createByErrorMessage("商品添加失败");
                    }
                    int i = appGoodsMapper.insertAppGoods(goods);
                    if (i > 0) {
                        if (appGoods.getRecommend() != null && appGoods.getRecommend() == 1) {
                            iSyLabelTypeService.savaHDKLabel(info.getData());
                        }
                        //更新商品lucene索引
                        updateIndex(goods, "add");
                        // this.updateAppGoods(goods);
                        return ServerResponse.createBySuccessCodeMessage(200, "商品添加成功，从好单库拉取");
                    } else return ServerResponse.createByErrorMessage("商品添加失败，从好单库拉取商品失败！");
                }
            }

        }

        //如果好单库不存在去淘宝查
        List<NTbkItem> items = taoBaoUtils.getTaoBaoItemId(itemId);
        if (CollectionUtils.isNotEmpty(items)) {
            for (NTbkItem nTbkItem : items) {
                AppGoods goods = tbGoodsToAppGoogs(nTbkItem);
                goods = getMoneyInfoByGoodsId(com, goods);
                goods.setAddUserId(userId);
                if (StringUtils.isNotNull(itempic)) {
                    goods.setItempic(itempic);
                }
                if (StringUtils.isNotNull(itemtitle)) {
                    goods.setItemshorttitle(itemtitle);
                }
                if (StringUtils.isNotNull(fqcat)) {
                    goods.setFqcat(fqcat);
                }
                if (appGoods.getRecommend() != null) {
                    goods.setRecommend(appGoods.getRecommend());
                }
                goods.setSort(appGoods.getSort());
                goods.setMsg(appGoods.getMsg());
//                    goods.setCreateTime(new Timestamp(System.currentTimeMillis()));
//                    goods.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                if (goods.getItemendprice() < 0) {
                    return ServerResponse.createByErrorMessage("商品添加失败");
                }
                int i = appGoodsMapper.insertAppGoods(goods);
                if (i > 0) {
                    //更新商品lucene索引
                    updateIndex(goods, "add");
                    //  this.updateAppGoods(goods);
                    return ServerResponse.createBySuccessCodeMessage(200, "商品添加成功，从淘宝拉取");
                } else return ServerResponse.createByErrorMessage("商品添加失败，从淘宝拉取商品失败");
            }
        }
        return ServerResponse.createByErrorMessage("该商品不存在!");
    }

    /**
     * 更新商品lucene索引
     *
     * @param appGoods
     */
    @Override
    public void updateLuceneAppGoods(AppGoods appGoods) {
        try {
            String appGood = JSONObject.toJSONString(appGoods);
            HttpClient httpclient = HttpClients.createDefault();
            String url = ApiEnum.EUREKA_URL + "/eureke/lucene/addIndex";
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(appGood, "UTF-8"));
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateIndex(AppGoods appGoods, String type) {
        Map map = new HashMap();
        map.put("type", type);
        map.put("appGoods", appGoods);
        TopicMessage message = new TopicMessage(JSON.toJSON(map).toString().getBytes(), RocketConfig.TAG);
        TopicMessage pubResultMsg = rocketmqProducerInit.getProducer().publishMessage(message);
        log.info(new Date() + " Send mq message success. Topic is:" + RocketConfig.TOPIC + ", msgId is: " + pubResultMsg.getMessageId()
                + ", bodyMD5 is: " + pubResultMsg.getMessageBodyMD5() + ",boby:" + pubResultMsg.getMessageBodyString());
    }

    @Override
    public void deleteIndex(String itemids, String type) {
        Map map = new HashMap();
        map.put("type", type);
        map.put("itemids", itemids);
        TopicMessage message = new TopicMessage(JSON.toJSON(map).toString().getBytes(), RocketConfig.TAG);
        TopicMessage pubResultMsg = rocketmqProducerInit.getProducer().publishMessage(message);
        log.info(new Date() + " Send mq message success. Topic is:" + RocketConfig.TOPIC + ", msgId is: " + pubResultMsg.getMessageId()
                + ", bodyMD5 is: " + pubResultMsg.getMessageBodyMD5() + ",boby:" + pubResultMsg.getMessageBodyString());
    }

    @Override
    public int updateBatchByItemId(AppGoods appGoods) {
        return appGoodsMapper.updateBatchByItemId(appGoods);
    }

    @Override
    public AppGoods selectAppGoodsByIdHitCount(Long itemId) {
        return appGoodsMapper.selectAppGoodsByIdHitCount(itemId);
    }

    @Override
    public Integer updateAppGoodsByIdHitCount(Long tableId, int hotCount) {
        return appGoodsMapper.updateAppGoodsByIdHitCount(tableId, hotCount);
    }

    @Override
    public void deleteTljGoodsfree() {
        appGoodsMapper.deleteTljGoodsfree();
    }

    @Override
    @Async
    public void deleteAppGoodsByAddUser(String addUserId, Date time) {

        appGoodsMapper.deleteAppGoodsByAddUser(addUserId, time);
    }

    @Override
    public AppGoods selectByOrderId(Long orderId) {
        return appGoodsMapper.selectByOrderId(orderId);
    }

    private AppGoods tbGoodsToAppGoogs(NTbkItem nTbkItem) {
        AppGoods appGoods = HDKUtils.getAppGoodsFromTB(nTbkItem);
        TbkPrivilege privilege = taoBaoUtils.getPrivilegeItemId(Long.valueOf(appGoods.getItemid() == null ? "0" : appGoods.getItemid()));
        appGoods.setCouponmoney(Double.valueOf(privilege.getCouponInfo() == null ? "0" : privilege.getCouponInfo()));
        appGoods.setCouponstarttime(privilege.getCouponStartTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponStartTime()).toString());
        appGoods.setCouponendtime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
        appGoods.setEndTime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
        BigDecimal itemendprice = BigDecimalUtils.Format(
                new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
                        .subtract(new BigDecimal(privilege.getCouponInfo() == null ? "0" : privilege.getCouponInfo()))
        );
        appGoods.setItemendprice(itemendprice.doubleValue());
        appGoods.setTkrates(privilege.getMaxCommissionRate());
        appGoods.setItemprice(nTbkItem.getZkFinalPrice().toString());

        appGoods.setTkmoney(BigDecimalUtils.FanliMoney(privilege.getMaxCommissionRate(), itemendprice).toString());
        return appGoods;
    }

    /**
     * 查询商品的优惠劵，折扣价，返佣比例，返佣等信息
     *
     * @param com
     * @param dataBean
     * @return
     */
    public AppGoods getMoneyInfoByGoodsId(AppCompany com, AppGoods dataBean) {
        return getMoneyInfoByGoodsId(null, com, dataBean);
    }

    /**
     * 查询商品的优惠劵，折扣价，返佣比例，返佣等信息
     *
     * @param com
     * @param dataBean
     * @return
     */
    public AppGoods getMoneyInfoByGoodsId(NTbkItem item, AppCompany com, AppGoods dataBean) {

        try {
            if (item == null || item.getNumIid() == null) {
                ServerResponse<List<NTbkItem>> response_ = taoBaoService.getSearchItemIdDetail(dataBean.getItemid());
                if (response_ != null && response_.getStatus() == 200 && response_.getData() != null && response_.getData().size() > 0) {
                    item = response_.getData().get(0);
                }
            }
            if (item != null) {
                //调用的是高佣的接口实时转链计算的佣金
                String str_ = "";
                TbkPrivilegeGetResponse tbkPrivilegeGetResponse = sessionController.tbkPrivilegeGetResponse(Long.parseLong(dataBean.getItemid()),
                        Long.parseLong(com.getGeneralizePid().split("_")[2]),
                        Long.parseLong(com.getGeneralizePid().split("_")[3]),
                        com.getTaoBaoScheme().getAppSession());

                if (tbkPrivilegeGetResponse != null) {
                    str_ = JSON.toJSONString(tbkPrivilegeGetResponse);
                }
                if (StringUtils.isNull(dataBean.getTaobaoImage())) {
                    if (item.getSmallImages() != null && item.getSmallImages().size() > 0) {
                        dataBean.setTaobaoImage(item.getSmallImages().toString().replace("[", "").
                                replace("]", ""));
                    }
                }

                if (str_ != null) {
                    TbkPrivilegeGetInfo info = JsonUtils.getJsonToBean(str_, TbkPrivilegeGetInfo.class);
                    if (info == null || info.getResult() == null || info.getResult().getData() == null) {
                        return dataBean;
                    }
                    TbkPrivilegeGetInfo.TbkPrivilege tbkPrivilege = info.getResult().getData();

//										appGoods_new.setTableId(appGoods.getTableId());
//                    dataBean.setShopDsr(item.getShopDsr());
                    dataBean.setTkmoney(item.getZkFinalPrice());
                    dataBean.setItemsale(Integer.parseInt(item.getVolume().toString()));
                    String coupon = RegUtils.getreGex(tbkPrivilege.getCouponInfo() == null ? "减0元" : tbkPrivilege.getCouponInfo(), "(?<=减)[0-9]*(?=元)");
                    coupon = coupon == null ? "0" : coupon;
                    if ("0".equals(coupon) && dataBean.getCouponmoney() > 0d) {

                    } else {
                        dataBean.setCouponmoney(NumberUtils.toInt(coupon));
                    }
                    dataBean.setCouponstarttime(tbkPrivilege.getCouponStartTime() == null ? String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(tbkPrivilege.getCouponStartTime()));
                    dataBean.setCouponendtime(tbkPrivilege.getCouponEndTime() == null ? String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(tbkPrivilege.getCouponEndTime()));
                    dataBean.setEndTime(tbkPrivilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(tbkPrivilege.getCouponEndTime()).toString());

                    dataBean.setCouponurl("0".equalsIgnoreCase(coupon) ? tbkPrivilege.getItemUrl() : tbkPrivilege.getCouponClickUrl());
//
                    //佣金和返后价计算规则
                    //券后价  = 原价 - 优惠券金额
                    //返利金额 = 券后价 * 佣金比例（佣金比例是%要除100）
                    //返后价 = 原价 - 返利金额


//                        dataBean.setItemendprice(BigDecimalUtils.Format(
//                                Double.valueOf(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
//                                        -
//                                        Double.valueOf(coupon)).doubleValue());
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                    .subtract(new BigDecimal(coupon))
                    );
                    String zkFinalPrice = dataBean.getItemprice() == null ? item.getZkFinalPrice() : dataBean.getItemprice();
                    BigDecimal itemendPrice = dataBean.getItemendprice() == null ? itemendprice : new BigDecimal(dataBean.getItemendprice());

                    if (itemendPrice.compareTo(new BigDecimal(0)) >= 0) {
                        dataBean.setItemprice(zkFinalPrice);
                        dataBean.setItemendprice(itemendPrice.doubleValue());

                        String tkMoney =
                                BigDecimalUtils.FanliMoney(tbkPrivilege.getMaxCommissionRate(),
                                        itemendPrice).toString();
                        dataBean.setTkmoney(tkMoney);
                        dataBean.setFreeShipment(item.getFreeShipment() != null && item.getFreeShipment() ? 1 : 0);
                        dataBean.setTkrates(tbkPrivilege.getMaxCommissionRate());
                    }

//								appGoods_new.setFanliUpdateTime((System.currentTimeMillis() / (1000 * 60 * 5)) + "");
                    dataBean.setFanliUpdateTime((System.currentTimeMillis()) + "");

                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return dataBean;


    }

    /**
     * 发送json数据并获取返回值
     *
     * @param message 消息
     * @return 发送消息的结果
     */
    @Override
    @Async
    public String sendSocketData(String url, String message) {
        try {
//			ConfigCache configCache = SpringContext.getConfigCache();
            //判断发送消息方式
            if (1 == 1) {//StaticConf.MSG_SEND_TYPE_HTTP.equalsIgnoreCase(configCache.getMSG_SEND_TYPE())){// http
//                String url = String.format("http://%s:%s", "192.168.31.216", "8089");
//				if(configCache.isUSE_TOKEN()){// 使用token
//
//				}
//                try {
//                    Thread.sleep(1000 * 5);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }

                long authTime = System.currentTimeMillis() / 1000;
                String key = "productAdd" + ":" + authTime;
                String authToken = DigestUtils.md5DigestAsHex(key.getBytes(StandardCharsets.UTF_8));
                JSONObject jsonObject = JSON.parseObject(message);
                jsonObject.put("authTime", authTime);
                jsonObject.put("authToken", authToken);
                message = jsonObject.toJSONString();

                log.debug("发送的json文本：" + message);
                try {
                    String result = WebUtil.post(url, message);
                    log.debug("返回结果:" + result);
                    return result;
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public List<AppGoods> selectGoodsList(Integer minId, Integer end, Integer cid) {
        List<AppGoods> goods = appGoodsMapper.selectGoodsList(minId, end, cid);
        if (goods.size() == 0) {
            return null;
        }
        return goods;
    }

    @Override
    public List<AppGoods> getUpdateItem(String minId, Integer end, Integer cid) {
        List<AppGoods> goods = appGoodsMapper.getUpdateItem(minId, end, cid);
        if (goods == null || goods.size() == 0) {
            return null;
        }
        return goods;
    }

    @Override
    public List<AppGoods> findItem(Long userId, Integer end, String updateTime, Integer classifyId) {
        List<AppGoods> goods = appGoodsMapper.findItem(userId, end, updateTime, classifyId);
        if (goods == null || goods.size() == 0) {
            return null;
        }
        return goods;
    }

    @Override
    public List<AppGoods> selectItem(Long userId, String itemid, Integer classifyId) {
        List<AppGoods> goods = appGoodsMapper.selectItem(userId, itemid, classifyId);
        if (goods == null || goods.size() == 0) {
            return null;
        }
        return goods;
    }

    @Override
    public List<AppGoodsVo> kingKongSonList(Integer star, Integer end, Integer cid, Integer kType) {
        List<AppGoods> appGoodsList = null;
        //1今日爆款
        if (kType == 1) {
            appGoodsList = appGoodsMapper.kingKongSonList(star, end, cid, "2");
        } else if (kType == 2) {
            //2是白菜专区
            appGoodsList = appGoodsMapper.kingKongSonList(star, end, cid, "9");
        } else if (kType == 3) {
            //3是聚划算
            appGoodsList = appGoodsMapper.kingKongSonList(star, end, cid, "3");
        } else if (kType == 4) {
            //4是淘抢购
            appGoodsList = appGoodsMapper.kingKongSonList(star, end, cid, "4");
        } else {
            return null;
        }
        if (appGoodsList == null) {
            return null;
        }

        List<AppGoodsVo> appGoodsVo = taoBaoService.getAppGoodsVo(null, appGoodsList, null, null, null);
        return appGoodsVo;
    }


    @Override
//    @Transactional
    public ServerResponse updateTopAppGoods(Map map) {
        Long tableId = MapUtils.getLong(map, "tableId");
        Integer itemTop = MapUtils.getInteger(map, "itemTop");
        String itemid = MapUtils.getString(map, "itemid");
        if (tableId == null || itemTop == null || StringUtils.isNull(itemid))
            return ServerResponse.createByErrorMessage("参数错误");
        //根据表id更新置顶状态
        AppGoods newAppGoods = new AppGoods();
        newAppGoods.setTableId(tableId);
        newAppGoods.setItemTop(itemTop);
        int i = appGoodsMapper.updateAppGoods(newAppGoods);
        if (i > 0) {
            if (itemTop == 1) {
                //添加置顶商品
                AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(itemid);
                if (appGoods != null) {
                    GoodsTop goodsTop = new GoodsTop();
                    goodsTop.setGoodsPlatform(1);
                    goodsTop.setCompanyId(1);
                    goodsTop.setGoodsName(appGoods.getItemshorttitle());
                    goodsTop.setGoodsPictureUrl(appGoods.getItempic());
                    goodsTop.setGoodsTitle(appGoods.getItemtitle());
                    goodsTop.setGoodsDecription(appGoods.getItemshorttitle());
                    goodsTop.setGoodsTopStage(2);
                    goodsTop.setGoodsId(itemid);
                    int i2 = iGoodsTopService.insertSelective(goodsTop);
                    if (i2 > 0) return ServerResponse.createBySuccessMessage("商品置顶成功");
                }
            } else if (itemTop == 2) {
                //删除商品置顶
                int i3 = iGoodsTopService.deleteByGoodsIdReturnInt(itemid);
                String messsage = "取消商品置顶成功!";
                if (i3 <= 0) messsage = messsage + " 删除置顶商品失败";
                return ServerResponse.createBySuccessMessage(messsage);
            }

        }
        return ServerResponse.createByErrorMessage("商品置顶状态修改失败");
    }

    public static void main(String[] args) {

        String a = "https://detail.tmall.com/item.htm?id=583405411993";

        String substring = a.substring(a.lastIndexOf("=") + 1);

    }
}
